﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyVoteMVC.Service;
using MyVoteMVC.Common;
using MyVoteMVC.Models;
using System.Web.Security;
using System.Web.Routing;
using MyVoteMVC.Domain;

namespace MyVoteMVC.Controllers
{
    public class UserController : Controller
    {
        public IFormsAuthenticationService FormsService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }

            base.Initialize(requestContext);
        }

        public ActionResult Register(string UserName)
        {
            IUserService userService = Factory.GetInstance<IUserService>();
            VT_Users pUser;
            userService.Register(UserName, UserName, UserName, out pUser);

            FormsService.SignIn(UserName, pUser.User_ID);
            return Content("{success:true, msg:'" + UserName + "'}");
        }

        public ActionResult Login(string UserName, string UserPass)
        {
            IUserService userService = Factory.GetInstance<IUserService>();
            var pUser = userService.UserLogin(UserName, UserPass);
            if (null != pUser)
            {
                FormsService.SignIn(pUser.User_Name, pUser.User_ID);
                return Content("{success:true, msg:'" + pUser.User_Name + "'}");
            }
            else
                return Content("{success:false}");
           
        }

        public ActionResult ModifyUserPass(string OldPass, string NewPass)
        {
            FormsIdentity pIdentity = (FormsIdentity)HttpContext.User.Identity;
            FormsAuthenticationTicket pTicket = pIdentity.Ticket;

            IUserService userService = Factory.GetInstance<IUserService>();
            var pResult = userService.ChangePassword(pTicket.Name, OldPass, NewPass);
            if (pResult)
                return Content("{success:true}");
            else
                return Content("{success:false}");
        }

        public ActionResult ForgetUserPass(string UserName)
        {
            IUserService userService = Factory.GetInstance<IUserService>();
            var pResult = userService.ForgotPassword(UserName);
            if (pResult)
                return Content("{success:true}");
            else
                return Content("{success:false}");
        }

    }
}
